<?php
/**
 * KePHP, Keep PHP easy!
 */

namespace Gitee\Db\Gitee;

use Gitee\Cache\DataIndexCache;
use Gitee\Cache\DataIndexModelImpl;
use Ke\Adm\Model;
use Ke\Utils\Failure;
use Ke\Utils\Success;

/**
 * Class App
 * tableName 'gitee_app'
 *
 * // class properties
 *
 * @property int    $id            主键
 * @property string $name          应用访问名
 * @property string $title         应用标题
 * @property string $base_url      应用网址
 * @property string $login_url     登录网址
 * @property string $client_id     授权客户端ID
 * @property string $client_secret 授权密钥
 * @property mixed  $roles         授权权限
 * @property int    $created_at    创建时间
 * @property int    $updated_at    更新时间
 * // class properties
 */
class App extends Model implements DataIndexModelImpl
{
	
	protected static $pk = 'id';
	
	protected static $pkAutoInc = true;
	
	protected static $tableName = 'gitee_app';
	
	protected static $columns = [
	
	];
	
	protected static $cacheSource = 'default';
	
	public static function dbColumns()
	{
		// database columns
		return [
			'id'            => ['label' => '主键', 'int' => 1, 'pk' => 1, 'autoInc' => 1],
			'name'          => ['label' => '应用访问名', 'max' => 32, 'default' => ''],
			'title'         => ['label' => '应用标题', 'max' => 64, 'default' => ''],
			'base_url'      => ['label' => '应用网址', 'max' => 128, 'default' => ''],
			'login_url'     => ['label' => '登录网址', 'max' => 128, 'default' => ''],
			'client_id'     => ['label' => '授权客户端ID', 'max' => 64, 'default' => ''],
			'client_secret' => ['label' => '授权密钥', 'max' => 64, 'default' => ''],
			'roles'         => ['label' => '授权权限'],
			'created_at'    => ['label' => '创建时间', 'timestamp' => 1, self::ON_CREATE => 'now'],
			'updated_at'    => ['label' => '更新时间', 'timestamp' => 1, self::ON_UPDATE => 'now'],
		];
		// database columns
	}
	
	protected $_originalData = [];
	
	protected function validateSave($process, array &$data)
	{
		if ($process === self::ON_UPDATE) {
			$this->setOriginalData($this->getShadowData());
		}
	}
	
	protected function afterSave($process, array &$data)
	{
		// 先更新索引，清理本地的原始数据
		static::index()->updateItem($this, true);
		$this->saveCache();
	}
	
	protected function afterDestroy()
	{
		static::index()->destroyItem($this, true);
		$this->destroyCache();
	}
	
	/**
	 * @return DataIndexCache
	 */
	public static function index()
	{
		return DataIndexCache::loadCache(static::class);
	}
	
	/**
	 * @param string $value
	 * @return \Gitee\Db\Gitee\App
	 */
	public static function loadByName(string $value)
	{
		$id = static::index()->getIndexData('name', $value);
		return static::loadCache($id);
	}
	
	/**
	 * @param string $value
	 * @return \Gitee\Db\Gitee\App
	 */
	public static function loadByClientId(string $value)
	{
		$id = static::index()->getIndexData('client_id', $value);
		return static::loadCache($id);
	}
	
	public static function getIndexFields(): array
	{
		return ['name', 'client_id'];
	}
	
	public static function getIndexVersion(): string
	{
		return '0.0.2';
	}
	
	public function setOriginalData(array $data = null)
	{
		$this->_originalData = $data ?? [];
		return $this;
	}
	
	public function getOriginalData(): array
	{
		return $this->_originalData;
	}
	
	public function clearOriginalData()
	{
		$this->_originalData = [];
		return $this;
	}
	
	public function saveToken(array $data = null)
	{
		if ($this->isNew())
			return new Failure('无效的码云应用程序');
		$data = $data ?? [];
		if (empty($data) || empty($data['access_token']) || empty($data['expires_in']))
			return new Failure('Token数据无效！');
		$token = new App_Token($data);
		$token->app_id = $this->getPk();
		if ($token->save()) {
			$_SESSION[$this->getSessionTokenKey()] = $token->getPk();
			return new Success('码云Token保存成功！');
		}
		return new Failure('码云Token保存失败！');
	}
	
	public function getSessionTokenKey()
	{
		return 'gitee_token_id';
	}
	
	public function getSessionToken(): App_Token
	{
		return App_Token::loadCache($_SESSION[$this->getSessionTokenKey()] ?? null);
	}
}
